from flask import Flask, jsonify
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from datetime import timedelta
from config import Config
from models import db
from routes import auth_bp, admin_bp, problems_bp, homeworks_bp, submissions_bp, courses_bp, llm_bp, assistant_bp
from routes.statistics import statistics_bp
from routes.judge import judge_bp
from middleware import register_middleware
try:
    from routes.classes import classes_bp
    from routes.assignments import assignments_bp
    from routes.teachers import teachers_bp
except ImportError:
    # 如果相对导入失败，尝试绝对导入
    import sys
    import os
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    from routes.classes import classes_bp
    from routes.assignments import assignments_bp
    from routes.teachers import teachers_bp
import os
import traceback
import logging

# 直接设置环境变量
os.environ['DEEPSEEK_API_KEY'] = 'sk-dc730ad23eac45279a0458965505bc68'
os.environ['LLM_API_KEY'] = 'sk-dc730ad23eac45279a0458965505bc68'

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 设置全局超时配置
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=app.config.get('REQUEST_TIMEOUT', 600))
    
    # 禁用URL末尾斜杠重定向
    app.url_map.strict_slashes = False
    
    # 初始化扩展
    db.init_app(app)
    CORS(app, 
         origins=["http://localhost:3000", "http://localhost:3001", "http://localhost:3002", "http://localhost:5173"],
         supports_credentials=True,
         methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
         allow_headers=["Content-Type", "Authorization", "X-Requested-With"])
    jwt = JWTManager(app)
    
    # 配置JWT，允许OPTIONS请求跳过认证
    @jwt.unauthorized_loader
    def unauthorized_response(callback):
        return jsonify({"error": "需要认证"}), 401
    
    @jwt.invalid_token_loader
    def invalid_token_response(callback):
        return jsonify({"error": "无效的token"}), 401
    
    @jwt.expired_token_loader
    def expired_token_callback(jwt_header, jwt_payload):
        return jsonify({"error": "token已过期"}), 401
    
    # 注册蓝图
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(problems_bp, url_prefix='/problems')
    app.register_blueprint(homeworks_bp, url_prefix='/homeworks')
    app.register_blueprint(submissions_bp, url_prefix='/submissions')
    app.register_blueprint(courses_bp, url_prefix='/courses')
    app.register_blueprint(llm_bp, url_prefix='/llm')
    app.register_blueprint(assistant_bp, url_prefix='/assistant')
    app.register_blueprint(statistics_bp, url_prefix='/statistics')
    app.register_blueprint(classes_bp, url_prefix='/classes')
    app.register_blueprint(assignments_bp, url_prefix='/assignments')
    app.register_blueprint(teachers_bp, url_prefix='/teachers')
    app.register_blueprint(judge_bp, url_prefix='/judge')
    
    # 注册中间件
    register_middleware(app)
    
    # 根路由
    @app.route('/')
    def index():
        return jsonify({"message": "智能OJ系统后端运行中！"})
    
    # 健康检查路由
    @app.route('/health')
    def health():
        return jsonify({"status": "healthy", "message": "智能OJ系统后端运行正常"})
    
    # 错误处理
    @app.errorhandler(404)
    def not_found(error):
        logger.error(f"404错误: {error}")
        return jsonify({"error": "接口不存在"}), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        logger.error(f"500错误: {error}")
        logger.error(f"错误详情: {traceback.format_exc()}")
        return jsonify({"error": "服务器内部错误", "details": str(error)}), 500
    
    # 全局异常处理
    @app.errorhandler(Exception)
    def handle_exception(e):
        logger.error(f"未处理的异常: {e}")
        logger.error(f"异常详情: {traceback.format_exc()}")
        return jsonify({"error": "服务器错误", "details": str(e)}), 500
    
    return app

if __name__ == '__main__':
    app = create_app()
    
    # 创建数据库表（如果不存在）
    with app.app_context():
        try:
            db.create_all()
            print("数据库表已创建/检查完成")
            print("请运行 python migrate_db.py 来添加缺失的字段")
            print("或运行 python init_db.py 来重新初始化数据库")
        except Exception as e:
            print(f"数据库初始化错误: {e}")
            print(f"错误详情: {traceback.format_exc()}")
    
    app.run(debug=True, host='0.0.0.0', port=5000)
